package com.xxl.job.executor.xxljob.autoregister.service;

import com.xxl.job.executor.xxljob.autoregister.dao.XxlJobGroupDao;
import com.xxl.job.executor.xxljob.autoregister.dao.XxlJobInfoDao;
import com.xxl.job.executor.xxljob.autoregister.model.XxlJobGroup;
import com.xxl.job.executor.xxljob.autoregister.model.XxlJobInfo;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Component;


/**
 * @author lukaidong
 * @date 2024/02/29
 * @description
 */
@Component
public class XxlJobAutoRegister extends AbstractXxlJobAutoRegister {

    private static Logger logger = LoggerFactory.getLogger(XxlJobAutoRegister.class);

    private final XxlJobGroupDao xxlJobGroupDao;
    private final XxlJobInfoDao xxlJobInfoDao;

    public XxlJobAutoRegister(RedisTemplate<String, String> redisTemplate, XxlJobGroupDao xxlJobGroupDao, XxlJobInfoDao xxlJobInfoDao) {
        super(redisTemplate);
        this.xxlJobGroupDao = xxlJobGroupDao;
        this.xxlJobInfoDao = xxlJobInfoDao;
    }

    @Override
    public int computeExecuteGroupIdIfAbsent(String appname, String title) {
        XxlJobGroup group = xxlJobGroupDao.getGroupByAppNameAndTitle(appname, title);
        if (group == null) {
            group = new XxlJobGroup(appname, title);
            xxlJobGroupDao.save(group);
        }
        return group.getId();
    }

    @Override
    protected void scheduleUpdate(int jobId, int triggerStatus) {
        xxlJobInfoDao.scheduleUpdate(jobId, triggerStatus);
    }

    @Override
    protected XxlJobInfo selectJobByGroupAndHandler(int groupId, String jobName) {
        return xxlJobInfoDao.selectJobByGroupAndHandler(groupId, jobName);
    }


    @Override
    protected void saveJobInfo(XxlJobInfo xxlJobInfo) {
        try {
            xxlJobInfoDao.save(xxlJobInfo);
        } catch (Exception e) {
            logger.error("保存任务失败：", e);
        }
    }
}
